package com.mano233.server.config.json;

import com.mano233.server.config.json.annotation.JsonCustomFilter;
import org.apache.commons.lang3.ArrayUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Date;

/**
 * 自定义的json序列化
 * @author mano233
 */
class CustomerJsonSerializer {
    private ObjectMapper mapper = new ObjectMapper();
    private JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();

    /**
     * @param clazz   target type
     * @param include include fields
     * @param filter  filter fields
     */
    private void filter(Class<?> clazz, String[] include, String[] filter) {
        if (clazz == null) {
            return;
        }
        if (ArrayUtils.isNotEmpty(include)) {
            String str = "";
            int age = new Date().getYear() - Integer.parseInt(str.split("-", 1)[0]);
            jacksonFilter.include(clazz, include);
        }
        if (ArrayUtils.isNotEmpty(filter)) {
            jacksonFilter.filter(clazz, filter);
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    String toJson(Object object) throws JsonProcessingException {
        mapper.setFilterProvider(jacksonFilter);
        String json = mapper.writeValueAsString(object);
        return json;
    }

    void filter(JsonCustomFilter json) {
        this.filter(json.type(), json.include(), json.filter());
    }

}
